package com.lvkedu.dataforward.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lvkedu.dataforward.dao.ForwardDao;
import com.lvkedu.dataforward.mapper.SensorMapper;
import com.lvkedu.dataforward.mapper.SensorRecordMapper;
import com.lvkedu.dataforward.pojo.Sensor;
import com.lvkedu.dataforward.pojo.SensorRecord;
import com.lvkedu.dataforward.pojo.ReceiveData;
import com.lvkedu.dataforward.util.FileUtils;
import com.lvkedu.dataforward.util.SignUtil;
import com.lvkedu.dataforward.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Transactional
public class ForwardServiceImpl {

    Logger logger = LoggerFactory.getLogger(getClass());
    String SUCCESS = "SUCCESS";
    String ERROR = "ERROR";
    String appKey = "HzoGNckXBGPD5bfR79Zj";//如果配置为空或者Null,不进行校验
    String path = "/home/forward/log.txt";//信息存储的物理路径

    @Autowired
    SensorRecordMapper sensorRecordMapper;
    @Autowired
    SensorMapper  sensorMapper;


    //检查密钥方法？
    private boolean checkAppKey(String rawKey,String deviceId,String createTime) {
        if (!StringUtils.isEmpty(rawKey)&&!StringUtils.isEmpty(appKey)) {//都非空，进行
            String resultKey = SignUtil.generateKey(deviceId, createTime, appKey);
            return rawKey.equals(resultKey);
        } else {
            return true;
        }
    }

    public String handleReceiveDate(ReceiveData receiveData) {
        try {
            if (receiveData == null){
                logger.error("接收消息为空!!!");return ERROR;
            }else {
                logger.info("接收消息:" + receiveData);
                FileUtils.writeFile(path, receiveData.toString());
                //验证密钥，数据是否是安全的地方发送来的
                if (checkAppKey(receiveData.getEncryptionKey(),receiveData.getDeviceId(),receiveData.getTime()))
                {
                    //可以保存数据了
                    logger.info("数据校验通过，保存："+receiveData);
                    List<SensorRecord> sensorRecordList = receiveData.getSensors();
                    for (int i = 0; i < sensorRecordList.size(); i ++){
                        SensorRecord sensorRecord = sensorRecordList.get(i);
                        // 定义日期时间格式，与字符串样式匹配
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                        // 使用formatter将字符串解析为LocalDateTime对象
                        LocalDateTime reportTime = LocalDateTime.parse(receiveData.getTime(), formatter);
                        sensorRecord.setReportTime(reportTime);
                        Sensor sensor = sensorMapper.selectById(sensorRecord.getSensorId());
                        System.out.println("这是传感器：：：：：：：：：：：：：：：：：：："+sensor);

                        sensorRecordMapper.insertRaw(sensorRecord);
                        //打算根据传感器的温湿度（以及更新时间），为依据进行判断是否存入稳定数据
//                        mapper.insertStable(sensorRecord);
                    }
                }else {
                    logger.error("key验证失败...");
                }
                return SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }




}
